<?php
require_once('inc_wtfaq.php');
	$dist = sprintf("ROUND(3956000 * 1.609344 * 2 * ASIN(SQRT(POWER(SIN((x(geocoords)-%s)*pi()/180 / 2), 2) +  COS(x(geocoords) * pi()/180) *  COS(x(geocoords) * pi()/180) *  POWER(SIN((y(geocoords) - %s) * pi()/180 / 2), 2)  )))",
			mysql_real_escape_string($_GET['latitude']),
			mysql_real_escape_string($_GET['longitude']));
				
				;
	$query = "SELECT wtfaq_wtfaq.id, location, title, $dist as distance, question, answer, x(geocoords) as latitude, y(geocoords) as longitude
				FROM wtfaq_wtfaq 
				INNER JOIN wtfaq_question ON wtfaq_question.wtfaq_id = wtfaq_wtfaq.id
				WHERE  $dist <= 1000
				ORDER BY wtfaq_question.id";		
				
	$result = mysql_query($query);
	
	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "\n";
		$message .= 'Whole query: ' . $query;
		print '{"status":"error", "msg": "'.$message.'"}';
	}

	$faqs = array();
	while ($row = mysql_fetch_assoc($result)) {
			$faqs[$row['id']][] = $row;
	}
	
	if (count($faqs) == 0) {
			// als er geen faqs in de buurt zijn dan de standaard FAQ tonen
			$dist = sprintf("ROUND(3956000 * 1.609344 * 2 * ASIN(SQRT(POWER(SIN((x(geocoords)-%s)*pi()/180 / 2), 2) +  COS(x(geocoords) * pi()/180) *  COS(x(geocoords) * pi()/180) *  POWER(SIN((y(geocoords) - %s) * pi()/180 / 2), 2)  )))",
			mysql_real_escape_string($_GET['latitude']),
			mysql_real_escape_string($_GET['longitude']));
		
			$query = "SELECT wtfaq_wtfaq.id, location, title, $dist as distance, question, answer, x(geocoords) as latitude, y(geocoords) as longitude
				FROM wtfaq_wtfaq 
				INNER JOIN wtfaq_question ON wtfaq_question.wtfaq_id = wtfaq_wtfaq.id
				WHERE  wtfaq_wtfaq.id = 8
				ORDER BY wtfaq_question.id";		
				
			$result = mysql_query($query);
			
			if (!$result) {
				$message  = 'Invalid query: ' . mysql_error() . "\n";
				$message .= 'Whole query: ' . $query;
				print '{"status":"error", "msg": "'.$message.'"}';
			}

			$faqs = array();
			while ($row = mysql_fetch_assoc($result)) {
					$faqs[$row['id']][] = $row;
			}
			print '{"status": "ok", "msg": "bla", "faqs":'.json_encode($faqs).'}';
	}
	else {
		print '{"status": "ok", "msg": "bla", "faqs":'.json_encode($faqs).'}';
	}
?>